/*******************************************************************************

Copyright (c) 2003, Robert Cowham and Vaccaperna Systems Ltd.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1.  Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL VACCAPERNA SYSTEMS LTD. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*******************************************************************************/

/*******************************************************************************
 * Name:	p4.cpp
 *
 * Author:	Robert Cowham <robert@vaccaperna.co.uk>
 *
 * Description: 
 *		Implementation of p4 - the COM class and thus external interface.
 *
 ******************************************************************************/

#include "stdafx.h"
#include <time.h>
#include "P4com.h"
#include "p4.h"

#include "TraceUtils.h"

#define CheckInitialized() \
	if (!m_Initialized) return Error("p4 init method not called!");

/////////////////////////////////////////////////////////////////////////////
// p4

STDMETHODIMP p4::InterfaceSupportsErrorInfo(REFIID riid)
{
	if (riid == IID_Ip4)
		return S_OK;
	return E_FAIL;
}


STDMETHODIMP p4::get_Charset(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetCharset()).Detach();
	return S_OK;
}

STDMETHODIMP p4::put_Charset(BSTR newVal)
{
	m_client.SetCharset(newVal);
	return S_OK;
}

STDMETHODIMP p4::get_Client(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetClient()).Detach();
	return S_OK;
}

STDMETHODIMP p4::put_Client(BSTR newVal)
{
	m_client.SetClient(newVal);
	return S_OK;
}

STDMETHODIMP p4::get_Cwd(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetCwd()).Detach();
	return S_OK;
}

STDMETHODIMP p4::put_Cwd(BSTR newVal)
{
	m_client.SetCwd(newVal);
	return S_OK;
}

STDMETHODIMP p4::get_Host(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetHost()).Detach();
	return S_OK;
}

STDMETHODIMP p4::put_Host(BSTR newVal)
{
	m_client.SetHost(newVal);
	return S_OK;
}

STDMETHODIMP p4::get_Language(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetLanguage()).Detach();
	return S_OK;
}

STDMETHODIMP p4::put_Language(BSTR newVal)
{
	m_client.SetLanguage(newVal);
	return S_OK;
}

STDMETHODIMP p4::get_Os(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetOs()).Detach();
	return S_OK;
}

STDMETHODIMP p4::get_Password(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetPassword()).Detach();
	return S_OK;
}

STDMETHODIMP p4::put_Password(BSTR newVal)
{
	m_client.SetPassword(newVal);
	return S_OK;
}

STDMETHODIMP p4::get_Port(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetPort()).Detach();
	return S_OK;
}

STDMETHODIMP p4::put_Port(BSTR newVal)
{
	m_client.SetPort(newVal);
	return S_OK;
}


STDMETHODIMP p4::get_User(BSTR *pVal)
{
	*pVal = CComBSTR(m_client.GetUser()).Detach();
	return S_OK;
}

STDMETHODIMP p4::put_User(BSTR newVal)
{
	m_client.SetUser(newVal);
	return S_OK;
}

STDMETHODIMP p4::put_Input(BSTR newVal)
{
	m_client.SetInput(newVal);
	return S_OK;
}

STDMETHODIMP p4::run(BSTR cmd, SAFEARRAY **valArray)
{
	StrBuf errMsg; 
	long result = m_client.Run(cmd, errMsg);

	HRESULT hr = ConvertArrayToSafeArray(m_client.m_ui.InfoArray(), valArray);
	if (hr)
		return hr;
	if (result)
	{
		errMsg = m_client.ErrorMsg();
		return Error(errMsg.Text(), GUID_NULL, MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 1));
	}
	else
	{
		errMsg = m_client.ErrorMsg();
		if (errMsg.Length() > 0)
		{
			return Error(errMsg.Text(), GUID_NULL, MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 2));
		}
	}
	return S_OK;
}

STDMETHODIMP p4::run_variant(BSTR cmd, VARIANT *pvaVariant)
{
	StrBuf errMsg; 
	long result = m_client.Run(cmd, errMsg);
	HRESULT hr = ConvertArrayToVariant(m_client.m_ui.InfoArray(), pvaVariant);
	if (hr)
		return hr;
	if (result)
	{
		errMsg = m_client.ErrorMsg();
		return Error(errMsg.Text(), GUID_NULL, MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 1));
	}
	else
	{
		errMsg = m_client.ErrorMsg();
		if (errMsg.Length() > 0)
		{
			return Error(errMsg.Text(), GUID_NULL, MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, 2));
		}
	}
	return S_OK;
}

STDMETHODIMP p4::get_Errors(SAFEARRAY **valArray)
{
	return ConvertArrayToSafeArray(m_client.m_ui.ErrorArray(), valArray);
}

STDMETHODIMP p4::get_Errors_variant(VARIANT *vArray)
{
	return ConvertArrayToVariant(m_client.m_ui.ErrorArray(), vArray);
}

STDMETHODIMP p4::get_Warnings(SAFEARRAY **valArray)
{
	return ConvertArrayToSafeArray(m_client.m_ui.WarningArray(), valArray);
}

STDMETHODIMP p4::get_Warnings_variant(VARIANT *vArray)
{
	return ConvertArrayToVariant(m_client.m_ui.WarningArray(), vArray);
}

STDMETHODIMP p4::Connect()
{
	StrBuf errMsg; 
	long result = m_client.Connect(errMsg);
	if (result)
		return Error(errMsg.Text());
	return S_OK;
}

STDMETHODIMP p4::Disconnect()
{
	m_client.Disconnect();
	return S_OK;
}

STDMETHODIMP p4::get_ExceptionLevel(long *pVal)
{
	*pVal = m_client.ExceptionLevel();
	return S_OK;
}

STDMETHODIMP p4::put_ExceptionLevel(long newVal)
{
	m_client.ExceptionLevel(newVal);
	return S_OK;
}

STDMETHODIMP p4::Tagged()
{
	m_client.Tagged();
	return S_OK;
}

STDMETHODIMP p4::ParseForms()
{
	m_client.ParseForms();
	return S_OK;
}

STDMETHODIMP p4::get_TempFilename(BSTR *pVal)
{
	StrBuf fn = m_client.m_ui.BinaryFileName();
	if (fn.Length() == 0)
		fn = m_client.m_ui.TextFileName();

	CComBSTR f = fn.Text();
	*pVal = f.Detach();
	return S_OK;
}

STDMETHODIMP p4::get_Var(BSTR varName, BSTR *pVal)
{
	USES_CONVERSION;
	CComBSTR val = m_client.m_ui.GetVar(W2CA(varName));
	*pVal = val.Detach();
	return S_OK;
}

STDMETHODIMP p4::put_Var(BSTR varName, BSTR newVal)
{
	USES_CONVERSION;
	m_client.m_ui.SetVar(W2CA(varName), newVal);
	return S_OK;
}

STDMETHODIMP p4::get_VarExists(BSTR varName, BOOL *pVal)
{
	USES_CONVERSION;
	*pVal = m_client.m_ui.VarExists(W2CA(varName));
	return S_OK;
}

STDMETHODIMP p4::get_ArrayVar(BSTR varName, SAFEARRAY **pVal)
{
	USES_CONVERSION;
	return ConvertArrayToSafeArray(m_client.m_ui.GetArrayVar(W2CA(varName)), pVal);
}

STDMETHODIMP p4::get_ArrayVar_variant(BSTR varName, VARIANT *vArray)
{
	USES_CONVERSION;
	return ConvertArrayToVariant(m_client.m_ui.GetArrayVar(W2CA(varName)), vArray);
}

STDMETHODIMP p4::put_ArrayVar(BSTR varName, SAFEARRAY **newVal)
{
	USES_CONVERSION;
	StrBufArray sba;
	if (!(NULL == newVal || NULL == *newVal))
	{
		ConvertSafeArrayToArray(*newVal, &sba);
	}
	m_client.m_ui.SetArrayVar(W2CA(varName), &sba);

	return S_OK;
}

STDMETHODIMP p4::put_ArrayVar_variant(BSTR varName, VARIANT newVal)
{
	USES_CONVERSION;
	StrBufArray sba;
	ConvertVariantToArray(newVal, &sba);
	m_client.m_ui.SetArrayVar(W2CA(varName), &sba);

	return S_OK;
}

void p4::ConvertSafeArrayToArray(SAFEARRAY *pArray, StrBufArray *result)
{
	BSTR *bstrArray;
    ::SafeArrayAccessData(pArray, (void **)&bstrArray);

    for (unsigned int i = 0; i < pArray->rgsabound->cElements; i++)
    {
		result->Put((void *)m_client.m_ui.TranslateFromBSTR(bstrArray[i]));
    }

    ::SafeArrayUnaccessData(pArray);
}

void p4::ConvertVariantToArray(const VARIANT &newVal, StrBufArray *result)
{
    if (!(newVal.vt & VT_ARRAY) || !(newVal.vt & VT_BSTR))
        return;

    // Extract the SAFEARRAY
    SAFEARRAY *pArray;
    if (newVal.vt & VT_BYREF)
        pArray = *(newVal.pparray);  // VBScript
    else
        pArray = newVal.parray;      // VB	

    // Read the data.
    if (pArray->fFeatures & FADF_VARIANT)            // SAFEARRAY of VARIANTS, i.e. VBScript.
    {
        VARIANT *bvarArray;
        ::SafeArrayAccessData(pArray, (void **)&bvarArray);

        for (unsigned int i = 0; i < pArray->rgsabound->cElements; i++)
        {
            if (bvarArray[i].vt != VT_NULL && 
                bvarArray[i].vt != VT_EMPTY && 
                bvarArray[i].vt == VT_BSTR)
            {
				result->Put((void*)m_client.m_ui.TranslateFromBSTR(bvarArray[i].bstrVal));
            }
        }

        ::SafeArrayUnaccessData(pArray);
    }
    else if (pArray->fFeatures & FADF_BSTR)          // SAFEARRAY of BSTRs, i.e. VB.
    {
        BSTR *bstrArray;
        ::SafeArrayAccessData(pArray, (void **)&bstrArray);

        for (unsigned int i = 0; i < pArray->rgsabound->cElements; i++)
        {
			result->Put((void*)m_client.m_ui.TranslateFromBSTR(bstrArray[i]));
        }

        ::SafeArrayUnaccessData(pArray);
    }
}

HRESULT p4::ConvertArrayToSafeArray(StrBufArray *sba, SAFEARRAY **ppArray)
{
    if (!ppArray)
        return E_POINTER;

    BSTR *bstrArray;
    SAFEARRAY *psa;
    SAFEARRAYBOUND bounds = { sba->Count(), 0 };
    StrBuf sb;

    psa = ::SafeArrayCreate(VT_BSTR, 1, &bounds);
    ::SafeArrayAccessData(psa, (void **)&bstrArray);

    for (int i = 0; i < sba->Count(); i++)
    {
		sb.Set((LPCSTR)sba->Get(i));
        bstrArray[i] = m_client.m_ui.TranslateToBSTR(&sb);
    }

    ::SafeArrayUnaccessData(psa);

    *ppArray = psa;

    return S_OK;
}

HRESULT p4::ConvertArrayToVariant(StrBufArray *sba, VARIANT *pvaVariant)
{
	// Use technique shown in:
	// http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q165/9/67.ASP&NoWebContent=1
    HRESULT hr = NOERROR;
    LPSAFEARRAY psa;
    SAFEARRAYBOUND rgsabound[]  = {sba->Count(), 0}; // 0-based
    int i;
	StrBuf sb;

    if (!pvaVariant)
    {
	    return E_INVALIDARG;
    }
    VariantInit(pvaVariant);
    psa = SafeArrayCreate(VT_VARIANT, 1, rgsabound);
    if (!psa)
    {
		return E_OUTOFMEMORY;
    }

    VARIANT *va = new VARIANT[sba->Count()];
	if (!va)
	{
		hr = E_OUTOFMEMORY;
		goto Error_Block;
	}
    for (i = 0; i < sba->Count(); i++)
    {
		VariantInit(&va[i]);
		V_VT(&va[i]) = VT_BSTR;
		sb.Set((LPCSTR)sba->Get(i));
	    V_BSTR(&va[i]) = m_client.m_ui.TranslateToBSTR(&sb);
	    if (!V_BSTR(&va[i]))
		{
			hr = E_OUTOFMEMORY;
			goto Error_Block;
		}
    }

    {
        //Plug references to the data into the SAFEARRAY
        LPVARIANT rgElems;
        if (FAILED(hr = SafeArrayAccessData(psa,(LPVOID*)&rgElems)))
	    {
	        goto Error_Block;
		}
		for (i = 0; i < sba->Count(); i++)
		{
			rgElems[i] = va[i];
		}
		SafeArrayUnaccessData(psa);
    }

    V_VT(pvaVariant) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pvaVariant) = psa;

    return S_OK;

Error_Block:
    for (i = 0; i < sba->Count(); i++)
    {
		if (V_BSTR(&va[i]))
		{
			VariantClear(&va[i]);
		}
    }
    return hr;
}

STDMETHODIMP p4::get_ServerVersion(long *pVal)
{
	*pVal = m_client.GetServerVersion();
	return S_OK;
}

STDMETHODIMP p4::FormatDateTime(long unixtime, BSTR *pVal)
{
    struct tm *t;
    TCHAR buf[100];

	time_t currentTime = unixtime;
    t = localtime(&currentTime);
	wsprintf(buf, _T("%04d/%02d/%02d %02d:%02d:%02d"),
            t->tm_year+1900, t->tm_mon+1, t->tm_mday,
            t->tm_hour, t->tm_min, t->tm_sec);

	CComBSTR f = buf;
	*pVal = f.Detach();
	return S_OK;
}

STDMETHODIMP p4::Dropped(long *pVal)
{
	*pVal = m_client.Dropped();
	return S_OK;
}
